package models

import (
	"time"
)

type Message struct {
	ID             int       `json:"id"`
	Content        string    `json:"content"`
	Type           int       `json:"type"`
	Sender         int       `json:"sender"`
	Receiver       int       `json:"receiver"`
	From           int       `json:"from"`
	Unread         int64     `json:"unread"`
	IsLate         int       `json:"is_late"`
	ConversationId int       `json:"conversation_id"`
	UpdatedAt      time.Time `json:"updated_at"`
	CreatedAt      time.Time `json:"created_at"`
}

func AddMessage(message Message) (err error) {
	//创建新消息前,将会话中标记最新消息的标记更新掉
	err = db.Model(&Message{}).Where("conversation_id =?", message.ConversationId).Update("is_late", 0).Error
	if err != nil {
		return
	}
	err = db.Create(&message).Error
	if err != nil {
		return
	}
	var conversation Conversation
	err = db.Where("id =?", message.ConversationId).First(&conversation).Error
	if err != nil {
		return
	}
	//设置最新消息时间
	conversation.LateMsgAt = time.Now()
	//累计未读消息
	if message.From == 1 {
		conversation.UserUnread++
	} else {
		conversation.GuestUnread++
	}
	err = db.Save(&conversation).Error

	return
}

func FindMessage(conversation_id int, pageNum int, pageSize int) (messages []Message, total int64, err error) {
	err = db.Where("conversation_id =?", conversation_id).
		Limit(pageSize).
		Offset((pageNum - 1) * pageSize).
		Order("created_at desc").
		Find(&messages).
		Error

	if err != nil {
		return
	}
	err = db.Model(Message{}).Where("conversation_id =?", conversation_id).Count(&total).Error

	return
}

func DelMessage(id int) (err error) {
	err = db.Where("id = ? ", id).Delete(&Message{}).Error

	return
}
